/**
 * @class NG.controllers.WorkspaceForm 
 * @extends Ext.Controller
 */
NG.controllers.WorkspaceForm = Ext.extend(Ext.Controller, {

	/**
	 * 
	 * @param {Object} options
	 * <ul>
	 * <li><b>animation</b> : String (Optional) 
	 * 		Panel switch style
	 * </ul>
	 */
    index: function(options) {
        app.views.viewport.setActiveItem(
            app.views.workspaceList, options.animation
        );
    },
    
	/**
	 * 
	 * @param {Object} options
	 */
    back: function(options) {
        app.views.viewport.setActiveItem(options.target, options.animation);
    },

	/**
	 * 
	 * @param {Object} options
	 */
    show: function(options) {
        var id = parseInt(options.id);
        var workspace = NG.stores.workspace.getById(id);
        if (workspace) {
    		var panel = new App.WorkspaceFormPopupPanel({
    			editable: true
    		});
    		panel.prepareForRecord(workspace);
    		panel.show();
        	
        } else {
        	alert(id + "'li proje bulunamadı!");
        }
    },
    
	/**
	 * <b>options</> param consists of<br>
	 * <li>form: FormPanel
	 * <li>sessionID: String
	 * <li>id: integer. workspace id.
	 * <li>workspace: NG.models.Workspace
	 * <li>callback: Object<br>
	 * 	successFn: Function
	 * 	failureFn: Function
	 * 
	 * @param {Object} options
	 */
	doSave: function (options) {
		
		function doOperation(workspace, id){
			//NG.stores.workspace.removeWorkspaceById(id); //delete old record, if exists
			//NG.stores.workspace.sync();
			//NG.stores.workspace.add(workspace);
			if (NG.stores.workspace.getById(id)) { //update the record
				var storeWorkspace = NG.stores.workspace.getById(id);
				storeWorkspace.data = workspace.data;
				storeWorkspace.setId(id);
			} else {
				NG.stores.workspace.add(workspace);				
			}
			NG.stores.workspace.sync();
			//Ext.Msg.hide();
			//Ext.Msg.alert('Mesaj', MSG_WS_SAVED);
			alert(MSG_WS_SAVED);
			Ext.dispatch({
				controller: app.controllers.workspaceForm,
				action: 'index'
			});
		}
		
		var workspace = options.workspace;
		var sessionID = options.sessionID;
		var id = options.id;
		
		if (!Ext.isEmpty(id) && NG.stores.workspace.getById(id)) { //update record if exists
			var oldWorkspace = NG.stores.workspace.getById(id);
			//incase of connection failure, set coordinates and tilesizeinpixel properties to updated model
			workspace.setProjectWholeWorld(oldWorkspace.getProjectWholeWorld());
			workspace.setTileSizeInPixel(oldWorkspace.getTileSizeInPixel());
		}
	
		if (!Ext.isEmpty(sessionID)) { //If connection established and a session id is gathered
			//alert("sesid:" + sessionID);
			var tiledProjectInfoCommand = new NG.command.TiledProjectInfo({
				workspaceName: workspace.getName(),
				runXmlUrl: workspace.getRunXmlUrl(),
				showLoading: false
			});

			
			NGServiceRequester.executeCommand(tiledProjectInfoCommand, sessionID, {
	        	requestFinished: function (response) {
	        		var tiledProjectInfoResponse = new NG.response.TiledProjectInfo({
	        			xmlData: response
	        		});
					
					workspace.setProjectWholeWorld(tiledProjectInfoResponse.getProjectWholeWorld());
					workspace.setTileSizeInPixel(tiledProjectInfoResponse.getTileSizeInPixel());
    	    		if (options.callback && Ext.isFunction(options.callback.successFn)) {
    	    			options.callback.successFn.call();
    	    		}    	    		
					doOperation(workspace, id);
	        	},
    	    	requestFail: function (response){
    	    		if (options.callback && Ext.isFunction(options.callback.failureFn)) {
    	    			options.callback.failureFn.call();
    	    		}
    	    	}			
			});			
		} else {
			doOperation(workspace, id);
		}
	},
    
	/**
	 * Saves workspace info.
	 * <b>options</> param consists of<br>
	 * <li>form: FormPanel
	 * <li>callback: Object<br>
	 * 	successFn: Function
	 * 	failureFn: Function
	 * 
	 * @param {Object} options
	 */	
    save: function(options) {
		var form = options.form;
		var workspace = Ext.ModelMgr.create(form.getValues(), 'NG.models.Workspace');
		var id = options.id;
		options.workspace = workspace;

        var errors = workspace.validate();
        var message = "";
        var controller = this;
        if(errors.isValid()){
			var session = NGServiceRequester.isAlreadyLoggedIn(workspace.getUsername(), workspace.getLoginUrl());
			if (session && session.isValid()) {
				options.sessionID = session.sessionID;
				controller.doSave(options);
			} else {
				NGServiceRequester.login(workspace.getUsername(), workspace.getPassword(), workspace.getLoginUrl(), {
					loginSuccess: function (sessionID) {
						console.log('Loginsucc: ' + sessionID);
						options.sessionID = sessionID;
						controller.doSave(options);								
					},
					loginFail: function () {
	    	    		if (options.callback && Ext.isFunction(options.callback.successFn)) {
	    	    			options.callback.successFn.call();
	    	    		}						
						//Ext.Msg.confirm(L_CONFIRM, MSG_NO_CONN_SAVE_CONFIRM, saveFailure);
						//new Ext.MessageBox({
							//floating: false
						//}).confirm(L_CONFIRM, MSG_NO_CONN_SAVE_CONFIRM, saveFailure, options.form);
						//function saveFailure(btn) {
						//	if (btn == "ok" || btn == "yes") {
						//		controller.doSave(options);
						//	}
						//}
						var r=confirm(MSG_NO_CONN_SAVE_CONFIRM);
						if (r==true) {
							controller.doSave(options);
						}
					}
				}, false); //false indicates that don't show loading for ajax request
			}
        } else {
            Ext.each(errors.items,function(rec,i){
                message += rec.message+"<br>";
            });
            Ext.Msg.alert("Geçerlilik", message, Ext.emptyFn);
            return false;
        }
    }

});

/**
 * 
 * @property app.controllers.workspaceForm
 */
app.controllers.workspaceForm = new NG.controllers.WorkspaceForm();